/*
 * @Descripttion: 
 * @version: 
 * @Author: guangyunl
 * @Date: 2024-03-09 02:38:34
 * @LastEditors: guangyunl
 * @LastEditTime: 2024-04-03 02:43:49
 */

"use strict";
const Service = require("egg").Service;
const axios = require("axios");

const { Op } = require("sequelize");

const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
const await = require("await-stream-ready/lib/await");
const sUploadAvatar = require("./s_uploadAvatar");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sActivitys extends Service {

  //活动查询
  async pc_s_query_activitys(params) {
    console.log("paramsUser:===============> ", params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);

      let where = {
        title: {
          [Op.like]: `%${params?.title ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
        type: {
          [Op.like]: `%${params?.type ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
        sort: {
          [Op.like]: `%${params?.sort ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
      };

      const result = await ctx.model.Activitys.findAndCountAll({
        where,
        include: [{
          model: ctx.model.Products,
        }],
        attributes: ["id", "title", "type", "discount", "sort", "createdAt", "updatedAt"],

        order: [["id", "ASC"]], // 排序

        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });

      await Journal(ctx, { operatorType: "活动信息 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: result?.count || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 活动信息查询");
      await Journal(ctx, { operatorType: "活动信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 根据活动id查询所有商品
  async pc_s_queryActivityProducts(params) {
    console.log("paramsUser:===============> ", params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);

      let where = {
        title: {
          [Op.like]: `%${params?.title ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
      };

      const result = await ctx.model.Products.findAndCountAll({
        where,
        include: [{
          model: ctx.model.Activitys,
          where: {
            id: params?.aid,
          }
        }],
        order: [["id", "ASC"]], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });

      await Journal(ctx, { operatorType: "活动商品信息 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: result?.count || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 活动商品信息");
      await Journal(ctx, { operatorType: "活动商品信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 批量挂载商品资源
  async pc_s_batchMount (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      // 1. 查询特定的活动
      const activitys = await ctx.model.Activitys.findByPk(params?.id);
      console.log('product: ', activitys);
      // 2. 查询要添加的资源
      const resourcesToAdd = await ctx.model.Products.findAll(
        {
          where: {
            id: { [Op.in]: params?.pids ?? [] },
          },
        },
      );
      console.log('resourcesToAdd: ', resourcesToAdd);
      //添加商品
      await activitys.addProducts(resourcesToAdd);
      //移除商品
      // await activitys.removeProducts(resourcesToAdd);
      
      await Journal(ctx, { operatorType: '活动商品信息 -> 批量挂载资源', code: 200 });
      response = successRes(200);
    } catch (error) {
      console.error(error, '<---- error - 活动商品信息批量挂载资源');
      await Journal(ctx, { operatorType: '活动商品信息 -> 批量挂载资源', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 移除商品资源
  async pc_s_batchRemove (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      // 1. 查询特定的活动
      const activitys = await ctx.model.Activitys.findByPk(params?.id);
      console.log('product: ', activitys);
      // 2. 查询要移除的资源
      const resourcesToRemove = await ctx.model.Products.findAll(
        {
          where: {
            id: params?.pid?? "",
          }, 
        },
      );
      console.log('resourcesToRemove: ', resourcesToRemove);

      //移除商品
      await activitys.removeProducts(resourcesToRemove);
      
      await Journal(ctx, { operatorType: '活动商品信息 -> 批量移除资源', code: 200 });
      response = successRes(200);
    } catch (error) {
      console.error(error, '<---- error - 活动商品信息批量移除资源');
      await Journal(ctx, { operatorType: '活动商品信息 -> 批量移除资源', code: 401 });
      response = failRes(401);
    }
    return response;
  }


  //活动新增
  async pc_s_create_activitys(params) {
    let response = null;
    const { ctx } = this;

    try {

      await ctx.model.Activitys.create(
        params,
        {
          attributes: {
            extends: ["id", "title", "type", "discount", "sort"],
          },
        } // 向数据库插入特定字段
      );

      await Journal(ctx, { operatorType: "活动新增 -> 新增", code: 200 });
      response = successRes();

    } catch (error) {
      console.error(error, "<---- error - 活动新增");
      // await transaction.rollback();
      await Journal(ctx, { operatorType: "活动新增 -> 新增", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  //活动修改
  async pc_s_update_activitys(params) {
    console.log(params, "<= params");
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Activitys.update(
        params,
        {
          where: { id: params.id },
          attributes: { extends: ["id"] },
        }
        // console.log(params, '<---- params - 活动修改数据')
      );

      await Journal(ctx, { operatorType: "活动修改 -> 编辑", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 活动修改");
      await Journal(ctx, { operatorType: "活动修改 -> 编辑", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 活动删除
  async pc_s_delete_activitys(params) {
    console.log(params, "<======= params");
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Activitys.destroy({
        where: { id: params.id },
      });
      await Journal(ctx, { operatorType: "活动删除 -> 删除", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 活动删除");
      await Journal(ctx, { operatorType: "活动删除 -> 删除", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 【小程序端】获取活动类型&商品
  async wa_s_queryActivitys(params) {
    let response = null;
    const { ctx } = this;
    try {
      const result = await ctx.model.Activitys.findAll({
        where: params,
        order: [["sort", "DESC"]],
        include: [{
          model: ctx.model.Products,
          through: { attributes: [] },
        }]
      })
      await Journal(ctx, { operatorType: "活动信息 -> 查询", code: 200 });
      response = successRes(result);
    } catch (error) {
      console.error(error, "<---- error - 活动信息查询");
      await Journal(ctx, { operatorType: "活动信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }


}
module.exports = sActivitys;
